<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>函数节流</title>
  <style type="text/css">
    #box {
      height: 3000px;
      background: red;
    }
  </style>
</head>

<body>
  <div id="box"></div>
  <script>
    window.onscroll = throttle(function () {
      console.log('haha');
    }, 1000);

    function throttle(fn, duration) {
      var _self = fn,
        timer,
        firstTime = true;

      return function () {
        var args = arguments;
        var _me = this;
        if (firstTime) {
          _self.apply(_me, arguments);
          return firstTime = false;
        }

        if (timer) {
          return false;
        }

        timer = setTimeout(function () {
          clearTimeout(timer);
          timer = null;
          _self.apply(_me, args);
        }, duration || 500);
      }
    }
  </script>
</body>

</html>